package com.example.api.config;

import org.springframework.web.servlet.mvc.condition.RequestCondition;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description 自定义版本匹配规则
 * @Author jie.zhao
 * @Date 2021/9/10 15:33
 */
public class ApiVersionRequestCondition implements RequestCondition<ApiVersionRequestCondition> {

    private final String apiVersion;
    private final ApiVersionConfigProperties apiVersionConfigProperties;

    public ApiVersionRequestCondition(String apiVersion, ApiVersionConfigProperties apiVersionConfigProperties) {
        this.apiVersion = apiVersion.trim();
        this.apiVersionConfigProperties = apiVersionConfigProperties;
    }

    @Override
    public ApiVersionRequestCondition combine(ApiVersionRequestCondition other) {
        // method annotation first
        return new ApiVersionRequestCondition(other.getApiVersion(), other.getApiVersionConfigProperties());
    }

    @Override
    public int compareTo(ApiVersionRequestCondition other, HttpServletRequest request) {
        return other.getApiVersion().compareTo(getApiVersion());
    }

    @Override
    public ApiVersionRequestCondition getMatchingCondition(HttpServletRequest request) {
        ApiTypeEnum type = apiVersionConfigProperties.getType();
        String version = null;
        switch (type) {
            case HEADER:
                version = request.getHeader(apiVersionConfigProperties.getHeader());
                break;
            case PARAM:
                version = request.getParameter(apiVersionConfigProperties.getParam());
                break;
        }
        boolean match = version != null && version.length() > 0 && version.trim().equals(apiVersion);
        if (match) {
            return this;
        }
        return null;
    }

    @Override
    public String toString() {
        return "@ApiVersion(" + apiVersion + ")";
    }

    public String getApiVersion() {
        return apiVersion;
    }

    public ApiVersionConfigProperties getApiVersionConfigProperties() {
        return apiVersionConfigProperties;
    }
}